from flask import jsonify, request
from app import db
from app.models.models import site_user, videos, order
from . import index_blu
import requests
import json
import urllib3


def get_openid(js_code):
    # js_code是前端给我传过来了，我用它换到openid再传回去
    appid = "wx9a6a17768c3dbef5"
    # 小程序id
    secret = "09420c9d85a5c49720369a6198acb31b"
    # 小程序密钥
    url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" % (
        appid, secret, js_code)
    urllib3.disable_warnings()
    # return requests.get(url, verify=False).content
    return requests.get(url, verify=False).content

@index_blu.route("/api/get_recommended_course",methods=["post"])
def get_recommended_courde():
    if request.method == 'POST':
        ret = db.session.query(videos).filter(videos.is_recommend == 'yes').all()
        new_dict = {}
        i = 0
        for w in ret:
            # 每个w是一个视频对象
            new_dict[i] = dict()
            new_dict[i]["name"] = w.video_name
            new_dict[i]["price"] = w.video_price
            new_dict[i]["fildID"] = w.fildID
            new_dict[i]["upload_data"] = w.upload_data
            i += 1
        return jsonify(new_dict)

@index_blu.route("/api/get_all_course_info", methods=["post"])
def get_all_course_info():
    """首页用到的获取所有课程信息"""
    if request.method == "POST":
        ret = db.session.query(videos).all()
        new_dict = {}
        i = 0
        for w in ret:
            # 每个w是一个视频对象
            new_dict[i] = dict()
            new_dict[i]["name"] = w.video_name
            new_dict[i]["price"] = w.video_price
            new_dict[i]["fildID"] = w.fildID
            new_dict[i]["upload_data"] = w.upload_data
            i += 1
        return jsonify(new_dict)


@index_blu.route("/api/add_shopping_cart", methods=["post"])
def add_shopping_cart():
    """加入购物车"""
    if request.method == "POST":
        open_id = request.json.get("open_id")
        text = request.json.get("text")
        ret = db.session.query(site_user).filter(site_user.open_id == open_id).first()
        if ret is None:
            return jsonify({'msg': '该用户未记录在库'})
        if ret.shopping_cart is None:
            ret.shopping_cart = " " + text
            db.session.commit()
        else:
            new_ret = ret.shopping_cart + " " + text
            ret.shopping_cart = new_ret
            db.session.commit()
        return jsonify({'msg': '加入成功'})


@index_blu.route("/api/order_finish", methods=["post"])
def order_finish():
    """将订单状态修改成已完成"""
    if request.method == "POST":
        # open_id = request.values.get("open_id")
        order_id = request.values.get("order_id")
        ret = db.session.query(order).filter(order.order_id == order_id).first()
        if ret is None:
            return jsonify({"msg": '未找到该订单'})
        ret.order_status = "finish"
        db.session.commit()
        return jsonify({"msg": '修改订单状态为已完成'})


@index_blu.route("/api/add_order", methods=["post"])
def add_order():
    """添加订单入库"""
    if request.method == "POST":
        open_id = request.json.get("open_id")
        order_id = request.json.get("order_id")
        text = request.json.get("text")
        ret = db.session.query(order).filter(order.order_id == order_id).first()
        text = text.replace("~", ' ')
        if ret is None:
            new_user = order(order_id=order_id, open_id=open_id, order_str=text, order_status="unfinish")
            db.session.add(new_user)
            db.session.commit()
            return jsonify({"msg": "添加订单完成"})
        else:
            return jsonify({"msg": '订单号已存在'})


@index_blu.route("/api/get_course_info", methods=["post"])
def get_course_info():
    """获取课程详情页面"""
    if request.method == "POST":
        course_name = request.json.get("course_name")
        ret = db.session.query(videos).filter(videos.video_name == course_name).first()
        if ret is None:
            return jsonify({"msg": "未加入该课程"})
        else:
            new_dict = {}
            new_dict["price"] = ret.video_price
            new_dict["sort"] = ret.video_sort
            new_dict["duration"] = ret.video_duration
            new_dict["upload_date"] = ret.upload_data
            new_dict["video_url"] = ret.url
            new_dict["fildID"] = ret.fildID
            return jsonify(new_dict)


@index_blu.route("/api/add_promission", methods=["post"])
def add_promission():
    """把权限加给用户"""
    if request.method == 'POST':
        text = request.json.get('text')
        open_id = request.json.get("open_id")
        if open_id == '':
            return jsonify({"msg": "open_id是空字符串"})
        else:
            ret = db.session.query(site_user).filter(site_user.open_id == open_id).first()
            if ret is None:
                return jsonify({"msg": "用户未记录", "open_id": open_id})

        ret = db.session.query(site_user).filter(site_user.open_id == open_id).first()
        text_list = text.split("~", -1)
        text_list = text_list[1:]
        if ret.promission is None:
            new_ret = ''
            for i in text_list:
                new_ret += " " + i
            ret.promission = new_ret
            db.session.commit()
        else:
            new_ret = ret.promission
            for i in text_list:
                new_ret += " " + i
            ret.promission = new_ret
            db.session.commit()
        return jsonify({"msg": '添加完成'})


@index_blu.route("/api/search", methods=["post"])
def search():
    """获取搜索内容"""
    if request.method == "POST":
        text = request.json.get("text")
        ret = db.session.query(videos).filter(videos.video_name.like("%" + text + "%")).all()
        print(ret)
        if len(ret) == 0:
            return jsonify({"msg": "搜索为空"})
        else:
            new_dict = {}
            i = 0
            for w in ret:
                # 每个w是一个视频对象
                new_dict[i] = dict()
                # print(new_dict)
                new_dict[i]["name"] = w.video_name
                new_dict[i]["price"] = w.video_price
                new_dict[i]["fildID"] = w.fildID
                i += 1
            return jsonify(new_dict)


@index_blu.route("/api/del_shopping_cart", methods=["post"])
def del_shopping_cart():
    """从购物车里删除东西"""
    if request.method == 'POST':
        text = request.json.get('text')
        open_id = request.json.get("open_id")
        if open_id == '':
            return jsonify({"msg": "open_id是空字符串"})
        else:
            ret = db.session.query(site_user).filter(site_user.open_id == open_id).first()
            if ret is None:
                return jsonify({"msg": "用户未记录", "open_id": open_id})
        text_list = text.split("~", -1)
        text_list = text_list[1:]
        for i in text_list:
            if i in ret.shopping_cart:
                ret = db.session.query(site_user).filter(site_user.open_id == open_id).first()
                ret.shopping_cart = ret.shopping_cart.replace(" " + i, "")
                db.session.commit()
        return jsonify({"msg": '删除完成'})


@index_blu.route("/api/get_shopping_cart", methods=["post"])
def get_shopping_cart():
    """获取购物车内容"""
    if request.method == "POST":
        openid_ret = request.values.get("open_id")
        if openid_ret == '':
            return jsonify({"msg": "open_id是空字符串"})
        else:
            ret = db.session.query(site_user).filter(site_user.open_id == openid_ret).first()
            if ret is None:
                return jsonify({"msg": "用户未记录", "open_id": openid_ret})
            if ret.shopping_cart is None or ret.shopping_cart == '':
                return jsonify({"msg": "购物车为空"})
            else:
                list_ret = ret.shopping_cart.split(" ", -1)
                list_ret = list_ret[1:]
                new_dict = {}
                for i in range(len(list_ret)):
                    # i是0，1，2，int
                    new_dict[i] = dict()
                    new_dict[i]["name"] = list_ret[i]
                    ret = db.session.query(videos).filter(videos.video_name == list_ret[i]).first()
                    new_dict[i]["price"] = ret.video_price
                    new_dict[i]["fildID"] = ret.fildID
                return jsonify(new_dict)


@index_blu.route("/api/get_promission", methods=["post"])
def get_promission():
    """获取已购买内容"""
    if request.method == "POST":
        openid_ret = request.values.get("open_id")
        if openid_ret == '':
            return jsonify({"msg": "open_id是空字符串"})
        else:
            ret = db.session.query(site_user).filter(site_user.open_id == openid_ret).first()
            if ret is None:
                return jsonify({"msg": "用户未记录", "open_id": openid_ret})
            if ret.promission is None or ret.promission == '':
                return jsonify({"msg": "已购买为空"})
            else:
                list_ret = ret.promission.split(" ", -1)
                list_ret = list_ret[1:]
                new_dict = {}
                for i in range(len(list_ret)):
                    # i是0，1，2，int
                    new_dict[i] = dict()
                    new_dict[i]["name"] = list_ret[i]
                    ret = db.session.query(videos).filter(videos.video_name == list_ret[i]).first()
                    new_dict[i]["price"] = ret.video_price
                    new_dict[i]["fildID"] = ret.fildID
                return jsonify(new_dict)


@index_blu.route("/api/get_profilephoto", methods=["post"])
def get_profilephoto():
    """get头像"""
    if request.method == "POST":
        openid_ret = request.values.get("open_id")
        if openid_ret == '':
            return jsonify({"msg": "open_id是空字符串"})
        else:
            ret = db.session.query(site_user).filter(site_user.open_id == openid_ret).first()
            if ret is None:
                return jsonify({"msg": "用户未记录", "open_id": openid_ret})
            if ret.user_profilephoto_url is None or ret.user_profilephoto_url == '':
                return jsonify({"msg": "用户未上传头像"})
            else:
                return jsonify({"fileID": ret.user_profilephoto_url})


@index_blu.route("/api/get_username", methods=["post", 'get'])
def get_username():
    """get用户名"""
    if request.method == "GET":
        openid_ret = request.values.get("open_id")
        if openid_ret == '':
            return jsonify({"msg": "open_id是空字符串"})
        else:
            ret = db.session.query(site_user).filter(site_user.open_id == openid_ret).first()
            if ret is None:
                return jsonify({"msg": "用户未记录", "open_id": openid_ret})
            if ret.user_id is None or ret.user_id == '':
                return jsonify({"msg": "用户未上传用户名"})
            else:
                return jsonify({"username": ret.user_id})


@index_blu.route("/api/upload_profilephoto", methods=["post"])
def api_upload_profilephoto():
    """上传头像"""
    if request.method == "POST":
        fileID_ret = request.values.get("fileID")
        openid_ret = request.values.get("open_id")
        # username_ret = request.values.get("username")
        if openid_ret == '':
            return jsonify({'msg': 'openid是空字符串'})
        if fileID_ret == '':
            return jsonify({'msg': 'fileid都是空字符串'})
        ret = db.session.query(site_user).filter(site_user.open_id == openid_ret).first()
        # 去数据库里看看open_Id有没有
        if ret is None:
            return jsonify({"msg": '该用户未记录', "用户open_Id": openid_ret})

        try:
            ret.user_profilephoto_url = fileID_ret
            db.session.commit()
            # 把fileID加到这个用户记录中
            return jsonify({"msg": 'fileID上传成功'})
        except:
            return jsonify({"msg": "fileID上传数据库时失败"})


@index_blu.route("/api/upload_username", methods=["post", 'get'])
def api_upload_username():
    """上传用户名"""
    if request.method == "POST":
        username_ret = request.json.get("username")
        openid_ret = request.json.get("open_id")
        print('----------', username_ret, openid_ret)
        if openid_ret == '':
            return jsonify({'msg': 'openid是空字符串'})
        if username_ret == '':
            return jsonify({'msg': 'username都是空字符串'})
        ret = db.session.query(site_user).filter(site_user.open_id == openid_ret).first()
        # 去数据库里看看open_Id有没有
        if ret is None:
            return jsonify({"msg": '该用户未记录', "用户open_Id": openid_ret})
        try:
            ret.user_id = username_ret
            db.session.commit()
            # 把fileID加到这个用户记录中
            return jsonify({"msg": 'username上传成功'})
        except:
            return jsonify({"msg": "username上传数据库时失败"})


@index_blu.route("/api/login", methods=["post"])
def api_login():
    if request.method == "POST":
        ret = request.values.get("code")
        datas = get_openid(ret)
        # 得到的数据里既有open_id，也有session_key(用不上的)
        # 现在是json格式
        dic = json.loads(datas)
        # 转化为字典格式
        open_id = dic.get("openid")
        # 从字典中取出open_id的值
        if open_id is None:
            return datas
        ret = db.session.query(site_user).filter(site_user.open_id == open_id).first()
        # 查查这个用户有没有被存进库中，没有就存进去
        if ret is None:
            new_user = site_user(open_id=open_id)
            db.session.add(new_user)
            db.session.commit()
        return datas

# @index_blu.route("/api/test", methods=["post"])
# def api_test():
#     if request.method == "POST":
#         ret = db.session.query(videos).filter(videos.video_name == "三国").first()
#         # print(ret.video_price)
#         data = {'price': ret.video_price, "sort": ret.video_sort}
#         return jsonify(data)
